from fastapi import APIRouter, Depends, status
from sqlalchemy.ext.asyncio import AsyncSession


from . import crud, schemas
from .dependencies import (
    find_user_by_token,
    get_bot_token_payload,
    get_user_by_token_depend,
)
from .tools import prepare_ads_for_bot
from scaner.core.config.log_config import MyLogger
from scaner.core.models import User, ADS, db_helper


router = APIRouter(tags=["tg_bot"])

main_logger = MyLogger("main")
logger = main_logger.getChild("bot_api")  # type: ignore


@router.post(
    "/create_reference/",
    status_code=status.HTTP_201_CREATED,
)
async def create_reference_route(
    data: schemas.UserBotToken,
    session: AsyncSession = Depends(db_helper.get_async_session),
):
    logger.info("Создание связи чата и пользователя")
    token = data.token
    payload = get_bot_token_payload(token=token)

    try:
        user: User = await find_user_by_token(
            token=token,
            session=session,
        )

        await crud.create_chat_reference(
            chat_id=payload["chat_id"],
            tg_user_id=payload["tg_user_id"],
            token=token,
            user=user,
            session=session,
        )
        return {"status": "Success"}

    except Exception as e:
        return {"status": "Error", "message": str(e)}


@router.get(
    "/get_ads_list/",
    status_code=status.HTTP_200_OK,
)
async def get_ads_list_route(
    user: User = Depends(get_user_by_token_depend),
    session: AsyncSession = Depends(db_helper.get_async_session),
):
    ads_list: list[ADS] = await crud.get_ads_for_bot(user=user, session=session)

    logger.info("Выдача результата, отформатированных для бота ")
    prepared_message: list[str] = prepare_ads_for_bot(ads_list)

    return {
        "status": "Success",
        "message": prepared_message,
    }
